﻿using MaterialManagement.Domain;
using MaterialManagement.Domain.MesWorkOrder;
using MaterialManagement.Infrastructure.Interface;
using Microsoft.Extensions.Configuration;

using SqlSugar;
using DbType = SqlSugar.DbType;

namespace MaterialManagement.Infrastructure.Implement
{
    public class DatabaseContext : IDatabaseContext
    {
        private readonly string _connectionString;
        public SqlSugarScope SqlSugar { get; }

        public SqlSugarScope SqlSugarScope => throw new NotImplementedException();

        public DatabaseContext(IConfiguration configuration)
        {
            _connectionString = configuration.GetValue<string>("erp");
            SqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.SqlServer,
                ConnectionString = _connectionString,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            },
            db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
            });
        }
        public void InitializeDatabase()
        {
            try
            {
                SqlSugar.CodeFirst.InitTables(
                    //typeof(MaterialInfoModel),
                    //typeof(MaterialInventoryModel),
                    //typeof(OutboundRecordModel),
                    //typeof(StorageRecordModel),
                    //typeof(PickingModel),
                    //typeof(MaterialWarehouseModel),
                    //typeof(ProcessInspectionModel),
                    //typeof(BOMInformationModel),
                    //typeof(BOMProductModel),
                    //typeof(BOMLogsModel)
                );

                Console.WriteLine("数据库表初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败: {ex.Message}");
                throw;
            }
        }
    }
}
